from mtp.model import *
from mtp.model import ObjBase
from mtp.lib.plugin import Plugin
from mtp.lib.base import *

PasswordsTable = Table('user_passwords', plugin_meta,
    Column('user_id', Integer, primary_key=True, autoincrement=False),
    Column('password', MD5Type),
)

class UserPassword(ObjBase):
    @classmethod
    def check(klass, user, password):
        userpass = klass.get(user.id)
        if not userpass:
            return False

        m = hashlib.md5()
        m.update(password)
        
        return (userpass.password == m.hexdigest())

mapper(UserPassword, PasswordsTable)


class AuthController(BaseController):
    def login_form(self):
        try:
            c.return_url = request.environ['paste.recursive.old_path_info'][0]
        except (KeyError, IndexError):
            c.return_url = '/'
        return render('/auth/login.html')        

    def login(self):
        username = request.POST.get('username')
        password = request.POST.get('password')
        if not username or not password:
            return render('/auth/login.html')

        user = User.getByUsername(username)

        admin = (username == config['mtp.config']['auth']['admin_user'] and 
            password == config['mtp.config']['auth']['admin_password'])
        
        if admin and not user:
            user = User(username=username)
            user.save()

        if not user:
            return render('/auth/login.html')          

        if not admin and not UserPassword.check(user, password):
            return render('/auth/login.html')

        session['user'] = user
        session.save()

        try:
            redirect_to(str(request.POST['return_url']))
        except KeyError:
            redirect_to(h.url_for('home'))
        
    def logout(self):
        if session.has_key('user'):
            del session['user']
            session.save()
        redirect_to('/')

    def permission_denied(self):
        return "perm denied"


class LocalPasswordAuthPlugin(Plugin):
    tables = [PasswordsTable]

    def __init__(self, **options):
        config['mtp.controllers']['auth'] = AuthController
        map = config['mtp.map']
        map.connect('login_form', 'login', controller='auth', action='login_form', 
                    conditions=dict(method=['GET']))
        map.connect('login', 'login', controller='auth', action='login',
                    conditions=dict(method=['POST']))
        map.connect('logout', 'logout', controller='auth', action='logout')
        map.connect('permission_denied', '/perimssion_denied', 
                    controller='auth', action='permission_denied')
        
        



